package silo.dungeonbuddy;

//import java.lang.*;
import java.io.*;
import java.net.*;
//import java.util.Vector;

class Client
{
	private String returnMessage = "DEFAULT";
	private String receivedMessage = "DEFAULT";
	private Start game;
	
	public Client(Start eGame)
	{
		game=eGame;
	}//constructor
	
	public void call()
	{
		try
		{
			//BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
			Socket clientSocket = new Socket(game.getServerIP(), 9000);
			clientSocket.setSoTimeout(500);
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			outToServer.writeBytes(returnMessage + '\n');
			returnMessage = game.compress(returnMessage);
			receivedMessage = inFromServer.readLine();
			receivedMessage = game.decompress(receivedMessage);
			clientSocket.close();
		}catch(Exception e)
		{
			
		}//catch
		try
		{
			if(returnMessage.contains("!MAP"))
			{
				InputMessage IM = new InputMessage(receivedMessage,game);
				IM.buildMap();
				String mess="";
				String userName=game.getUserName();
				Unit u = null;
				for(int i=0;i<game.getUnitList().size();i++)
				{
					try
					{
						u = (Unit)game.getUnitList().get(i);
						if(u.getOwner().equalsIgnoreCase(userName))
						{
							mess = u.toString();
							i = game.getUnitList().size();
						}
					}catch(Exception e)
					{
						mess="!NO UNIT FROM PLAYER,";
					}//catch
				}//next i
				if(u==null)
				{
					mess="!NO UNIT FROM PLAYER,";
				}
				returnMessage = "!UPDATE," + userName + "," + mess;
			}else if((returnMessage.contains("!UPDATE"))||(returnMessage.contains("!ENDTURN"))||(returnMessage.contains("!MISS"))||(returnMessage.contains("!HIT")))
			{
				InputMessage IM = new InputMessage(receivedMessage,game);
				IM.update();
				String mess="";
				String userName=game.getUserName();
				Unit u = null;
				for(int i=0;i<game.getUnitList().size();i++)
				{
					try
					{
						u = (Unit)game.getUnitList().get(i);
						if(u.getOwner().equalsIgnoreCase(userName))
						{
							mess = u.toString();
							i = game.getUnitList().size();
						}
					}catch(Exception e)
					{
						mess="!NO UNIT FROM PLAYER,";
					}//catch
				}//next i
				if(u==null)
				{
					mess="!NO UNIT FROM PLAYER,";
				}
				returnMessage = "!UPDATE," + userName + "," + mess;
			}
		}catch(Exception e)
		{
			System.out.println("ERROR!!  CODE 7" + e.getMessage());
		}//catch
	}//call
	
	//GETTERS
	public String getReturnMessage()
	{
		return returnMessage;
	}
	public String getReceivedMessage()
	{
		return receivedMessage;
	}
	
	//SETTERS
	public void setReturnMessage(String eMess)
	{
		returnMessage=eMess;
	}
	public void setReceivedMessage(String eMess)
	{
		receivedMessage=eMess;
	}
	
}//class Client